package easy.netty.net.rpc;

import easy.netty.net.core.Endpoint;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author cengy
 */
public abstract class RpcPeer
        extends Endpoint {

    private static final int RPC_MAX_LEN = 65535;
    private static final Logger
            logger = LoggerFactory.getLogger(RpcPeer.class);

    protected static final Map<String, RpcFuture> futureMap = new HashMap<>();

    @Override
    protected void initChannel0(Channel ch) throws Exception {

        final ChannelPipeline p = ch.pipeline();
        p.addLast(new LengthFieldBasedFrameDecoder(RPC_MAX_LEN, 0, 4, 0, 4))
                .addLast(new ObjectDecoder(ClassResolvers
                                .weakCachingConcurrentResolver(
                                        Thread.currentThread().getContextClassLoader())
                        )
                )
                .addLast(new LengthFieldPrepender(4))
                .addLast(new ObjectEncoder());
    }

}
